#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "src/json.h"

#ifdef __linux__
#include <sys/time.h>
unsigned long long reckon_usec(void)
{
	struct timeval mstime;
	unsigned long long us = 0;
	gettimeofday(&mstime, NULL);
	us = mstime.tv_sec * 1000000 + mstime.tv_usec;
	return us;
}
#else 
#define reckon_usec() 0
#endif 

/* for memory allocation test */
#if 1

static int count = 0;
static int use = 0;

void* test_malloc(size_t size)
{
	void* p;

	p = malloc(size + sizeof(int));
	if (p)
	{
		count++;
		*(int*)p = size;
		use += size;
	}
	return (void*)((char*)p + sizeof(int));
}

void test_free(void* block)
{
	void* p = block;
	p = (void *)((char*)p - sizeof(int));
	use -= *(int*)p;
	count--;
	free(p);
}

void check_used(void)
{
	printf("count = %d use = %d\r\n", count, use);
	if (count)
	{
		printf("***************************************************************\r\n");
		printf("************************* error *******************************\r\n");
		printf("***************************************************************\r\n");
	}
}
#else 
#define test_malloc malloc
#define test_free free
#define check_used()
#endif 

void test_dump(void)
{
	json_t json, t;

	/* create root node */
	json = json_create_object("root");

	/* Add to root node */
	json_add_string_to_object(json, "name", "json parser");
	json_add_string_to_object(json, "version", "1.6.0");
	json_add_string_to_object(json, "description", "This is a C language version of json streamlined parser.");
	json_add_string_to_object(json, "repository", "https://gitee.com/Lamdonn/json");

	/* Add an empty array to the root node */
	t = json_add_array_to_object(json, "keywords"); /* t receive added array */
	json_add_string_to_array(t, "json");
	json_add_string_to_array(t, "streamlined");
	json_add_string_to_array(t, "parser");

	/* Add an empty object to the root node */
	t = json_add_object_to_object(json, "others"); /* t receive added object */
	json_add_bool_to_object(t, "open", JSON_TRUE);
	json_add_string_to_object(t, "license", "GPL3.0");

	/* Dump JSON objects to a file */
	json_file_dump(json, "test.json");

	/* Delete after end of use */
	json_delete(json);
}

void test_load(void)
{
	json_t json, t;
	char *s = NULL;

	/* Load json file */
	json = json_file_load("test.json");
	if (!json) return;

	t = json_to_key(json, "name");
	if (json_isstring(t)) printf("module name: %s\r\n", json_value_string(t));

	t = json_to_key(json, "others", "open");
	if (json_isbool(t)) printf("open: %s\r\n", json_value_bool(t) ? "yes" : "no");

	t = json_to_index(json, 4, 1);
	if (json_isstring(t)) printf("keywords[1]: %s\r\n", json_value_string(t));

	/* Delete after end of use */
	json_delete(json);
}

int main()
{
	/* Used for testing memory usage */
	json_set_hooks(test_malloc, test_free, NULL);

	// test_dump();
	test_load();

	check_used();
	printf("%c\r\n", getchar());
    return 0;
}